<?php
class NewsManageController  extends Zone_Action{
	protected function fields(){
		$data = array(
			date_updated		=> array(
				type			=> 'NONE',
				default_value	=> mysql_date()
			),		
			updated_by_id	=> array(
				type			=> 'NONE',
				default_value	=> get_user_id()
			),		
			title => array(
				type 		=> 'CHAR',
				no_empty 	=> true,
				form_label 	=> 'Tiêu đề',
				default_value 	=> ''
			),
			desc => array(
				type 	   		=> 'TEXT',
				form_label 		=> 'Mô tả',
				default_value 	=> ''
			),
			content => array(
				type 	   		=> 'TEXT',
				form_label 		=> 'Nội dung',
				default_value 	=> ''
			),
			is_approve => array(
				type 	   		=> 'ENUM',
				form_label 		=> 'Duyệt',
				default_value 	=> 'no',
				value			=> array('yes','no')
			),
			parent_id		=> array(
				type		=> 'INT',
				form_label  => 'Loại dự án'				
			),
			date	=> array(
				type		=> 'DATETIME',				
				form_label 	=> 'Ngày hiện',
				no_empty	=> true	
			)
		);
		return $data;	
	}
	
	protected function fieldFile(){
		$data = array(
			files => array(
				type 	=> 'FILES',
				path	=> 'files/project/'
			)
		);
		return $data;	
	}
	
	public function initAction(){
		$this->set('folders',$this->Model->fetchAll("SELECT * FROM `news_cats` ORDER BY `ord`"));		
	}	
		
	public function indexAction(){
		$user_id = get_user_id();
		$vars = array();
		
		$order_by = "ORDER BY `a`.`date_created` DESC";
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('title','date','date_created','parent_id','created_by_id');
		
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$wheres = array();		
		$wheres[] = "`a`.`is_draft`='no'";

		
		$where = implode(" AND ",$wheres);		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`
			FROM  `news` as `a`
			WHERE $where");		
			
		$posts = $this->Model->fetchAll("SELECT 
				`a`.*,
				`b`.`title` as `parent_title`,
				`c`.`username` as `created_by_name`,
				`d`.`username` as `updated_by_name`,
				`c`.`is_deleted` as `created_is_deleted`,
				`d`.`is_deleted` as `updated_is_deleted`
			FROM  `news` as `a`
			LEFT JOIN `news_cats` as `b`
				ON `a`.`parent_id`=`b`.`ID`
			LEFT JOIN `users` as `c`
				ON `a`.`created_by_id`=`c`.`ID`
			LEFT JOIN `users` as `d`
				ON `a`.`updated_by_id`=`d`.`ID`
			WHERE $where $order_by $limit");
	
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#News/Manage?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));
	}

	/* Upload like ajax */
	public function imgAction(){
		$this->removeLayout();
		$user_id = get_user_id();		
		$id = get("ID",0);
		
		$post = $this->Model->fetchRow("SELECT * FROM `news` WHERE `ID`='$id'");
		if( !$post){
			return $this->setJSON(array(
				alert	=> 'Tin đã bị xóa hoặc không tồn tại.'
			));
		}
		
		if( isPost() ){
			loadClass("ZData");
			$f = new ZData();

			$f->addField(array(
				file => array(
					type 		=> 'FILE',
					path		=> 'files/news/',
					file_type	=> array('gif','png','jpg'),
					no_empty	=> true,
					resize		=> array(150,150)
				)
			));
			
			$data = $f->getData();		
			
			if( is_array( $data ) ){
				$file = $data['file'];
				if( $post['img'] ){
					@unlink("files/news/{$post['img']}");
				}
				
				$this->Model->update("news",array(
					img		=> $file[0]
				),"`ID`='$id'");				
				
				return $this->setJSON(array(
					content	=> "<img src='".baseUrl()."/files/news/{$file[0]}?".time()."'/>"
				));
			}else{
				return $this->setJSON(array(
					alert => $data
				));				
			}			
		}
		$this->setJSON(array(
			alert	=> 'Truy cập không được cho phép.'
		));
	}		
	
	public function addAction(){
		$user_id = get_user_id();		
		
		$post = $this->Model->fetchRow("SELECT * FROM `news` 
			WHERE `created_by_id`='$user_id' AND `is_draft`='yes' LIMIT 1");
			
		$user = $this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'");	
		$this->set('user',$user);	
			
		if( $post ){
			$news_id = $post['ID'];
			$files = $this->Model->fetchAll("SELECT * FROM `news_files` WHERE `news_id`='$project_id'");	
		}else{
			$this->Model->insert("news",array(
				is_draft		=> 'yes',
				created_by_id	=> $user_id							
			));
			$news_id = $this->Model->lastId();
			$post 	= array(
				ID	=> $news_id
			);
			$files	= array();
		}
		
		$this->set(array(
			user	=> $user,
			post	=> $post,
			files	=> $files
        ));
	
		if(isPost()){		
			$this->removeLayout();			
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->fields() );
			$data = $form->getData();			
			
			if( !is_array( $data )){					
				$this->setJSON(array(
					message => error($data)
				));		
			}
		
			if( !is_array($data) ){
				return $this->setJSON(array(
					message	=> error($data)
				));
			}
			$data['is_draft'] ='no';
			$data['date_created'] = mysql_date();
			$data['created_by_id'] = get_user_id();

			$files_selected = (array)$_POST['files'];
			$files = $this->Model->fetchAll("SELECT * FROM `news_files` WHERE `news_id`='$news_id'");
			
			foreach( $files as $f ){
				if( !in_array( $f['ID'], $files_selected ) ){
					$this->Model->delete('news_files',"`ID`='{$f['ID']}'");
					@unlink("files/news/{$f['name']}");
				}
			}				
			
			//update data
			$this->Model->update("news",$data,"`ID`='$news_id'");
			$this->setJSON(array(
				redirect =>	"#News/Index/View?ID=$news_id"
			));
		}		
	}

	public function editAction(){
		$user_id = get_user_id();
		$news_id = get('ID',0);	
		$post = $this
			->Model
			->fetchRow("SELECT * FROM `news` WHERE `ID`='$news_id' AND `is_draft`='no' LIMIT 1");
			
		if( !$post ){
			return $this->setContent(error('Tin không tồn tại hoặc đã bị xóa.'));
		}
		
		$user = $this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'");
		
		$this->set(array(
			user	=> $user,
			post	=> $post,
			files	=> $files
		));	
	
		if(isPost()){		
			$this->removeLayout();			
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->fields( $post ) );
			$data = $form->getData();			

			if( !is_array($data) ){
				return $this->setJSON(array(
					'message'	=> error($data)
				));
			}						
			
			//update data
			$this->Model->update("news",$data,"`ID`='$news_id'");
			
			$this->setJSON(array(
				redirect =>	"#News/Index/View?ID=$news_id"
			));
		}		
	}
	
	public function deleteAction(){
		$this->removeLayout();
		$news_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT * FROM `news` WHERE `ID`='$news_id'");
		
		if( !$post ){
			return $this->setJSON(array(
				alert => 'Tin đã bị xóa hoặc không tồn tại'			
			));
		}		
		
		$this->Model->delete('news',"`ID`='$news_id'");
		$this->Model->delete('news_comments',"`news_id`='$news_id'");
		@unlink("files/news/{$post['img']}");		
	
		return $this->setJSON(array(
			redirect	=> '#News/Manage'
		));		
	}	
	
	public function verifyAction(){
		$id = get('ID',0);
		$this->Model->update('news',array(
			is_approve => new Model_Expr("IF(is_approve='no','yes','no')")	
		),"`ID`='$id'");
		return $this->setJSON(array(
			redirect	=> '#News/Manage'
		));
	}	
}	